package com.kaifamiao.kfm.config.security;

import com.alibaba.fastjson.JSON;
import com.kaifamiao.kfm.util.JsonResult;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        int code = HttpStatus.UNAUTHORIZED.value();
        String msg = "请求访问：" +  request.getRequestURI() + "，认证失败，无法访问系统资源";;
        response.setStatus(200);
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        String str = JSON.toJSONString(JsonResult.error(code, msg));
        response.getWriter().print(str);
    }
}
